﻿using Microsoft.EntityFrameworkCore;
using Naruto.Repository;
using Naruto.TaskManagement.Entitys;
using Naruto.TaskManagement.Entitys.Enums;
using Naruto.TaskManagement.Entitys.Models;
using Naruto.TaskManagement.Entitys.VM;
using Naruto.TaskManagement.Infrastructure;
using Naruto.TaskManagement.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Naruto.TaskManagement.Repository
{
    public class TaskRecordRepository : ITaskRecordRepository
    {
        private readonly IRepository<TaskManagementContext> repository;

        private readonly IRepository<AuthCenterContext> authRepository;
        public TaskRecordRepository(IRepository<TaskManagementContext> _repository, IRepository<AuthCenterContext> _authRepository)
        {
            repository = _repository;
            authRepository = _authRepository;
        }
        public async Task Add(TaskRecord info)
        {
            await repository.Command<TaskRecord>().AddAsync(info);
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="status">任务状态</param>
        /// <param name="title"></param>
        /// <param name="type">记录的类型 1 查找我创建的  2 查找指派给我的任务</param>
        /// <param name="pageIndex"></param>
        /// <param name="userName">用户名</param>
        /// <param name="organizationId">组织id</param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<(List<TaskRecordGetListByPageViewModel> list, int count)> GetListByPage(int status, string organizationId, string title, int type, string userName, int pageIndex, int pageSize)
        {
            //获取同组织下的任务数据
            var userNameList = await (await authRepository.QueryAsync<User>()).Where(a => a.OrganizationId == organizationId).Select(a => a.UserName).ToListAsync();
            //查询任务
            var taskRecordQueryable = (await repository.QueryAsync<TaskRecord>()).Where(a => a.IsDelete == 0)
                  .Where(a => userNameList.Contains(a.CreateUser))
               .WhereIf(status >= 0, a => a.Status == status)
                .WhereIf(!title.IsNullEmpty(), a => a.Title.Contains(title))
                .WhereIf(type == 1, a => a.CreateUser == userName)
                .WhereIf(type == 2, a => a.AppointUser == userName)
                .AsNoTracking()
                 .Select<TaskRecord, TaskRecordGetListByPageViewModel>(new Dictionary<string, string>()
                 {
                     {"CreateDate" ,"CreateTime"}
                 });

            var count = await taskRecordQueryable.CountAsync();

            var list = await taskRecordQueryable.OrderByDescending(a => a.CreateDate).PageBy(pageIndex, pageSize).ToListAsync();

            return (list, count);
        }

        /// <summary>
        /// 获取数据总数
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="type"></param>
        /// <param name="userName">用户名</param>
        /// <param name="organizationId">组织id</param>
        /// <returns></returns>
        public async Task<GetListCountViewModel> GetListCount(string organizationId, string title, int type, string userName)
        {
            var result = new GetListCountViewModel();
            //获取同组织下的任务数据
            var userNameList = await (await authRepository.QueryAsync<User>()).Where(a => a.OrganizationId == organizationId).Select(a => a.UserName).ToListAsync();
            //查询任务
            var taskRecordQueryable = (await repository.QueryAsync<TaskRecord>()).Where(a => a.IsDelete == 0)
                  .Where(a => userNameList.Contains(a.CreateUser))
                .WhereIf(!title.IsNullEmpty(), a => a.Title.Contains(title))
                .WhereIf(type == 1, a => a.CreateUser == userName)
                .WhereIf(type == 2, a => a.AppointUser == userName)
                .AsNoTracking()
                 .Select(a => new
                 {
                     a.Status
                 });
            //总任务数
            result.allTaskCount = await taskRecordQueryable.CountAsync();
            //根据状态分组
            var group = taskRecordQueryable.GroupBy(a => a.Status).Select(a => new
            {
                a.Key,
                count = a.Count()
            });
            result.pendingTaskCount = await group.Where(a => a.Key == (int)TaskRecordStatusEnum.Pending).Select(a => a.count).FirstOrDefaultAsync();
            result.processedTaskCount = await group.Where(a => a.Key == (int)TaskRecordStatusEnum.Processed).Select(a => a.count).FirstOrDefaultAsync();
            result.cancelTaskCount = await group.Where(a => a.Key == (int)TaskRecordStatusEnum.Cancel).Select(a => a.count).FirstOrDefaultAsync();
            result.ignoreTaskCount = await group.Where(a => a.Key == (int)TaskRecordStatusEnum.Ignore).Select(a => a.count).FirstOrDefaultAsync();
            return result;
        }


        /// <summary>
        /// 获取单条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<TaskRecordGetByIdViewModel> GetById(string id)
        {
            var taskRecordQueryable = await repository.QueryAsync<TaskRecord>();

            return await taskRecordQueryable.Where(a => a.Id == id && a.IsDelete == 0)
                   .AsNoTracking()
                   .Select<TaskRecord, TaskRecordGetByIdViewModel>().FirstOrDefaultAsync();
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status">状态</param>
        /// <param name="operationUser">操作人</param>
        /// <returns></returns>
        public async Task UpdateStatus(string id, int status, string operationUser, string remark)
        {
            await repository.Command<TaskRecord>().UpdateAsync(a => a.Id == id,
                entity =>
                {
                    entity.OperationTime = DateTime.Now;
                    entity.OperationUser = operationUser;
                    entity.Status = status;
                    entity.Remark = remark;
                    return entity;
                });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pswd"></param>
        /// <returns></returns>
        public async Task Update(string id, string title, string description, int level, DateTime endDate, string appointUser)
        {
            await repository.Command<TaskRecord>()
                   .UpdateAsync(a => a.Id == id,
                   entity =>
                   {
                       entity.Title = title ?? "";
                       entity.Description = description ?? "";
                       entity.Level = level;
                       entity.EndDate = endDate;
                       entity.AppointUser = appointUser ?? "";
                       return entity;
                   });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task Delete(string id, string operationUser)
        {
            await repository.Command<TaskRecord>().UpdateAsync(a => a.Id == id, entity =>
            {
                entity.IsDelete = (int)TaskRecordDelEnum.Yes;
                entity.OperationUser = operationUser;
                entity.OperationTime = DateTime.Now;
                return entity;
            });
        }

        /// <summary>
        /// 获取单条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<TaskRecordGetAllByIdViewModel> GetAllById(string id)
        {
            var taskRecordQueryable = await repository.QueryAsync<TaskRecord>();
            return await taskRecordQueryable.Where(a => a.Id == id && a.IsDelete == 0)
                 .AsNoTracking()
                 .Select<TaskRecord, TaskRecordGetAllByIdViewModel>().FirstOrDefaultAsync();
        }

        /// <summary>
        /// 获取我的任务数
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public async Task<(int myCreateCount, int appointMyTask)> GetMyTaskCount(string userName)
        {
            var taskRecordQueryable = await repository.QueryAsync<TaskRecord>();
            //我创建的数
            var myCreateCount = await taskRecordQueryable.Where(a => a.CreateUser == userName && a.IsDelete == 0)
                 .AsNoTracking().CountAsync();

            //指派给我的
            var appointMyTaskCount = await taskRecordQueryable.Where(a => a.AppointUser == userName && a.IsDelete == 0)
                 .AsNoTracking().CountAsync();

            return (myCreateCount, appointMyTaskCount);
        }
    }
}
